//
//  NvCaptureViewController.m
//  SDKDemo
//
//  Created by ms20180425 on 2018/5/25.
//  Copyright © 2018年 meishe. All rights reserved.
//

#import "NvCaptureViewController.h"
#import "NvsStreamingContext.h"
#import "NvsLiveWindow.h"
#import "NvsAssetPackageManager.h"
#import "NvsCaptureVideoFx.h"
#import "NvsFxDescription.h"
#import <CoreMotion/CoreMotion.h>
#import "NvFilterCell.h"
#import "NvMoreFilterViewController.h"
#import <AVFoundation/AVFoundation.h>
#import "NvTipsView.h"
#import "NvCapturePopupView.h"
#import "NvBeautyView.h"
#ifdef NV_AI_FU
#import "NvsFaceEffectV1.h"
#import "authpack.h"
#endif
#import "NvAssetManager.h"
#import "NvEditViewController.h"
#import <Photos/PHPhotoLibrary.h>
#import "NvPsTitleCollectionViewCell.h"
#import <AssetsLibrary/AssetsLibrary.h>
#import <CoreMedia/CoreMedia.h>
#import "NvSDKUtils.h"

#import "NvCaptureFilterView.h"
#import "NvCaptureFilterModel.h"
#import "NvGraphicBtn.h"

@interface NvCaptureViewController ()<NvsStreamingContextDelegate, UICollectionViewDelegate, UICollectionViewDataSource,NvBeautyViewDelegate,NvCaptureFilterViewDelegate>

@property (nonatomic, strong) NvsStreamingContext *streamingContext;
@property (nonatomic, strong) NvsLiveWindow *liveWindow;
@property (nonatomic, strong) NvsLiveWindow *liveWindowBack;
@property (nonatomic, strong) NvsLiveWindow *curLiveWindow;//当前窗口
@property (nonatomic, assign) int currentDeviceIndex;
@property (nonatomic, assign) int currentPropsIndex;
@property (nonatomic, strong) NSMutableArray *videoPathArray;  //视频路径数组
@property (nonatomic, strong) NSMutableArray *psTitleArray;    //拍照、拍摄title数组
@property (nonatomic, assign) NSInteger cuttentInteger;        //当前拍照、拍摄对应的current
@property (nonatomic, strong) NSMutableArray *durationArray;   //断点拍摄每段视频的时长数组
@property (nonatomic, strong) NSString *pngPath;                //拍照的图片路径
@property (nonatomic, assign) int64_t duration;                //总拍摄时长
@property (nonatomic, assign) int64_t lastDuration;            //断点拍摄每次停止录制的时长，duration和durationArray需要用到
@property (nonatomic, assign) BOOL clickState;     //底部弹窗视图出现和消失
@property (nonatomic, strong) UIView *currentView; //底部当前弹窗视图
@property (nonatomic, strong) NvsCaptureVideoFx *fx;        //美颜特效
@property (nonatomic, strong) NvsCaptureVideoFx *fxARFace;  //人脸特效
@property (nonatomic, strong) NvsCaptureVideoFx *fxFilter;  //滤镜特效
@property (nonatomic, strong) NSMutableArray *beautyFxArray;
@property (nonatomic, strong) NSMutableArray *beautyTypeFxArray;
@property (nonatomic, assign) BOOL isBeautyFilter;
@property (nonatomic, assign) BOOL isHaveImage;             //防止出现一次拍照出现多张照片

//界面按钮
@property (nonatomic, strong) UIButton *backBtn;         //关闭
@property (nonatomic, strong) NvGraphicBtn *deviceBtn;       //切换摄像头
@property (nonatomic, strong) NvGraphicBtn *flashBtn;        //闪光灯
@property (nonatomic, strong) NvGraphicBtn *zoomBtn;         //变焦
@property (nonatomic, strong) NvGraphicBtn *exposureBtn;     //曝光
@property (nonatomic, strong) NvGraphicBtn *beautyBtn;       //美颜
@property (nonatomic, strong) NvGraphicBtn *filterBtn;       //滤镜
@property (nonatomic, strong) NvGraphicBtn *propsBtn;        //道具
@property (nonatomic, strong) UICollectionView *psTitleCollectionView; //拍照、拍摄切换视图
@property (nonatomic, strong) UIView *redView;           //红点
@property (nonatomic, strong) UIButton *shootingBtn;     //拍摄、拍照
@property (nonatomic, strong) UIButton *finishBtn;       //完成
@property (nonatomic, strong) UILabel  *timeLabel;       //录制时长
@property (nonatomic, strong) UIButton *deleteBtn;       //删除视频
@property (nonatomic, strong) UILabel  *videoCount;      //视频个数

//滤镜视图
@property (nonatomic, strong) NvCaptureFilterView  *filterView;   //滤镜视图
@property (nonatomic, strong) NvCaptureFilterModel *currentFilterModel; //当前滤镜
@property (nonatomic, strong) NSMutableArray *filterDataSource;//滤镜数组

//道具视图
@property (nonatomic, strong) UIView *propsPanelView;//最外层
@property (nonatomic, strong) UICollectionView *propsCollectionView;//道具滑动视图
@property (nonatomic, strong) NSMutableArray *propsDataSource;//道具数组
//权限视图
@property (nonatomic, strong) NvTipsView *permissions;
//相册权限视图
@property (nonatomic, strong) NvTipsView *photoView;
//手动对焦视图
@property (nonatomic, strong) UIImageView *focusView;
//变焦弹窗视图
@property (nonatomic, strong) NvCapturePopupView *zoomView;
//曝光弹窗视图
@property (nonatomic, strong) NvCapturePopupView *exposureView;
//美颜视图
@property (nonatomic, strong) NvBeautyView *beautyView;
//提示
@property (nonatomic, strong) NvTipsView *tipAIView;
//锐化、美颜滤镜开启提示
@property (nonatomic, strong) UILabel *tipLabel;
//照片预览视图
@property (nonatomic, strong) UIImageView *picturePreview;  //照片预览视图
@property (nonatomic, strong) UIView *picturePanelView;     //外层view

//-------//
@property (nonatomic, strong) NvAssetManager *assetManager;
@property (nonatomic, strong) NvsCaptureVideoFx* arfaceVideoFx;
//-------//
//摄像头的能力
@property (nonatomic, strong) NvsCaptureDeviceCapability *capability;

@end

static dispatch_once_t onceToken;
@implementation NvCaptureViewController {

}

- (void)dealloc{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
    NSLog(@"%s",__func__);
}

- (void)viewDidLoad {
    [super viewDidLoad];
    [self addObservers];
    self.videoPathArray = [NSMutableArray array];
    self.durationArray = [NSMutableArray array];
    self.filterDataSource = [NSMutableArray array];
    self.propsDataSource = [NSMutableArray array];
    self.psTitleArray = [NSMutableArray array];
    self.beautyFxArray = [NSMutableArray array];
    self.beautyTypeFxArray = [NSMutableArray array];
    _currentPropsIndex = 0;
    _cuttentInteger = 1;
    NvPsTitleModel *psTitleModel_1 = [NvPsTitleModel new];
    psTitleModel_1.name = @"单张";
    psTitleModel_1.selected = NO;
    NvPsTitleModel *psTitleModel_2 = [NvPsTitleModel new];
    psTitleModel_2.name = @"视频";
    psTitleModel_2.selected = YES;
    [self.psTitleArray addObject:psTitleModel_1];
    [self.psTitleArray addObject:psTitleModel_2];
    // 检查摄像头权限
    __weak typeof(self)weakSelf = self;
    AVAuthorizationStatus authStatus = [AVCaptureDevice authorizationStatusForMediaType:AVMediaTypeVideo];
    if (authStatus == AVAuthorizationStatusNotDetermined) {
        [AVCaptureDevice requestAccessForMediaType:AVMediaTypeVideo completionHandler:^(BOOL granted) {
            if (granted) {
                AVAuthorizationStatus audioAuthStatus = [AVCaptureDevice authorizationStatusForMediaType:AVMediaTypeAudio];
                if (audioAuthStatus == AVAuthorizationStatusNotDetermined) {
                    [AVCaptureDevice requestAccessForMediaType:AVMediaTypeAudio completionHandler:^(BOOL granted) {
                        if (granted) {
                            dispatch_async(dispatch_get_main_queue(), ^{
                                [weakSelf startupCapture];
                            });
                        } else {
                            // 提示麦克风权限未获得
                            dispatch_async(dispatch_get_main_queue(), ^{
                                [weakSelf startupCapture];
                                [weakSelf.view addSubview:weakSelf.permissions];
                            });
                        }
                    }];
                }
            } else {
                // 提示摄像头权限未获得
                dispatch_async(dispatch_get_main_queue(), ^{
                    [weakSelf.view addSubview:weakSelf.permissions];
                });
            }
        }];
    } else if (authStatus == AVAuthorizationStatusDenied) {
        // 提示摄像头权限未获得
        dispatch_async(dispatch_get_main_queue(), ^{
            [weakSelf.view addSubview:weakSelf.permissions];
        });
    } else {
        // 检查麦克风权限
        authStatus = [AVCaptureDevice authorizationStatusForMediaType:AVMediaTypeAudio];
        if (authStatus == AVAuthorizationStatusDenied) {
            // 提示麦克风权限未获得
            dispatch_async(dispatch_get_main_queue(), ^{
                [weakSelf.view addSubview:weakSelf.permissions];
            });
        }
        [weakSelf startupCapture];
    }
    
    NSArray *videoFxArray = @[@"NvsFilterNone",@"NvCaptureCartoon1",@"NvCaptureCartoon2",@"NvCaptureCartoon3"];
    NSArray *videoFxDisplayArray = @[@"无",@"漫画书",@"水墨",@"单色漫画"];
    for (int i = 0; i<videoFxArray.count; i++) {
        NvCaptureFilterModel *model = [[NvCaptureFilterModel alloc]init];
        model.selected = NO;
        model.displayName = videoFxDisplayArray[i];
        model.builtinName = @"Cartoon";
        if (i == 0) {
            model.coverName = videoFxArray[i];
        }else if(i >= 1 && i <= 3){
            model.coverName = [videoFxArray[i] stringByAppendingString:@".jpg"];
            if (i == 1) {
                model.strokeOnly = NO;
                model.grayscale = NO;
            }else if (i == 2){
                model.strokeOnly = YES;
                model.grayscale = NO;
            }else if (i == 3){
                model.strokeOnly = NO;
                model.grayscale = YES;
            }
        }
        [self.filterDataSource addObject:model];
    }
    
    self.assetManager = [NvAssetManager sharedInstance];
    dispatch_queue_t queue = dispatch_queue_create("net.bujige.testQueue", DISPATCH_QUEUE_SERIAL);
    dispatch_async(queue, ^{
        NSString *itemPath = [[[NSBundle mainBundle] bundlePath] stringByAppendingPathComponent:@"face1sticker"];
        [weakSelf.assetManager searchReservedAssets:ASSET_FACE1_STICKER bundlePath:itemPath];
        
        itemPath = [[[NSBundle mainBundle] bundlePath] stringByAppendingPathComponent:@"filter"];
        [weakSelf.assetManager searchReservedAssets:ASSET_FILTER bundlePath:itemPath];
        
        [weakSelf.assetManager searchLocalAssets:ASSET_FILTER];
        [weakSelf.assetManager searchLocalAssets:ASSET_FACE1_STICKER];
    });
}

- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    if ([_streamingContext getStreamingEngineState] != NvsStreamingEngineState_CapturePreview) {
        [self startCapturePreview];
        _streamingContext.delegate = self;
    }

    self.navigationController.navigationBar.hidden = YES;
    if (_currentView) {
        if ([self.currentView isEqual: self.filterView]) {
            [self updateFilters];
            [self.filterView configDataSource:self.filterDataSource];
        } else if (self.currentView == self.propsPanelView) {
            [self updateFaceStickers];
            [_propsCollectionView reloadData];
        }
    }
    if (_cuttentInteger == 0) {
        [_psTitleCollectionView setContentOffset:CGPointMake(-60 * SCREANSCALE, 0) animated:YES];
    }else{
        [_psTitleCollectionView setContentOffset:CGPointMake(0, 0) animated:YES];
    }
}

- (void)initReservedAssetName:(NvAsset *)asset {
    if ([asset isReserved]) {
        if ([asset.uuid isEqualToString:@"0FBCC8A1-C16E-4FEB-BBDE-D04B91D98A40"]) {
            asset.name = @"白皙";
        }
        if ([asset.uuid isEqualToString:@"6439CF7E-42D5-4239-8187-358323292FF4"]) {
            asset.name = @"冰激凌";
        }
        if ([asset.uuid isEqualToString:@"FAE50247-F14C-40CE-AD43-29CA3E604838"]) {
            asset.name = @"晨曦";
        }
        if ([asset.uuid isEqualToString:@"BD9D5DA9-581E-4B80-95D4-218D95FC78F2"]) {
            asset.name = @"风语";
        }
        if ([asset.uuid isEqualToString:@"394EB525-1B7A-4AA1-BBAD-3FD75527A60C"]) {
            asset.name = @"过往";
        }
        if ([asset.uuid isEqualToString:@"12FCD2E7-1F80-4DFC-A8FD-C820CF754855"]) {
            asset.name = @"雷耶斯";
        }
        if ([asset.uuid isEqualToString:@"D65436B7-D19F-47E0-9A2A-28CECC73D4F2"]) {
            asset.name = @"蜜桃";
        }
        if ([asset.uuid isEqualToString:@"B7F1F498-B310-4E2D-9A75-7D8AFBBC71D8"]) {
            asset.name = @"切尔西";
        }
        if ([asset.uuid isEqualToString:@"C9CE10F1-7C77-423C-BB7F-7F090C33D5C5"]) {
            asset.name = @"青春";
        }
        if ([asset.uuid isEqualToString:@"F7204261-41D8-454A-99DC-3522444739EB"]) {
            asset.name = @"斋普尔";
        }
        if ([asset.uuid isEqualToString:@"E1202F90-F2C8-4A14-BFCB-8F62BBD72F56"]) {
            asset.name = @"筑地";
        }
    }
}

// 防止锁屏
- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
    [[UIApplication sharedApplication] setIdleTimerDisabled:YES];
}

- (void)updateFilters {
    NSArray *array = [self.assetManager getUsableAssets:ASSET_FILTER aspectRatio:AspectRatio_All categoryId:NV_CATEGORY_ID_ALL];
    for (NvAsset *asset in array) {
        if ([self isFilterExist:asset.uuid]){
            continue;
        }
        if ([asset isReserved]) {
            NvCaptureFilterModel *filter = [[NvCaptureFilterModel alloc]init];
            [self initReservedAssetName:asset];
            filter.displayName = asset.name;
            filter.coverName = [asset.coverUrl absoluteString];
            filter.size = [NvSDKUtils getAssetPackageSizeString:asset.remotePackageSize];
            filter.draw = [NvSDKUtils getAssetAspectRatioString:asset.aspectRatio];
            filter.packageId = asset.uuid;
            [_filterDataSource insertObject:filter atIndex:4];
        }
    }
    for (NvAsset *asset in array) {
        if ([self isFilterExist:asset.uuid]){
            continue;
        }
        if (![asset isReserved]) {
            NvCaptureFilterModel *filter = [[NvCaptureFilterModel alloc]init];
            filter.displayName = asset.name;
            filter.coverName = [asset.coverUrl absoluteString];
            filter.size = [NvSDKUtils getAssetPackageSizeString:asset.remotePackageSize];
            filter.draw = [NvSDKUtils getAssetAspectRatioString:asset.aspectRatio];
            filter.packageId = asset.uuid;
            [_filterDataSource insertObject:filter atIndex:1];
        }
    }
}

- (void)updateFaceStickers {
    NSArray *array = [self.assetManager getUsableAssets:ASSET_FACE1_STICKER aspectRatio:AspectRatio_All categoryId:NV_CATEGORY_ID_ALL];
    for (NvAsset *asset in array) {
        if ([self isFaceStickerExist:asset.isReserved ? asset.bundledLocalDirPath : asset.localDirPath])
            continue;
        NvFilterItem *filter = NvFilterItem.new;
        filter.displayName = asset.name;
        filter.cover = [asset.coverUrl absoluteString];
        filter.size = [NvSDKUtils getAssetPackageSizeString:asset.remotePackageSize];
        filter.draw = [NvSDKUtils getAssetAspectRatioString:asset.aspectRatio];
        filter.package = asset.isReserved ? asset.bundledLocalDirPath : asset.localDirPath;
        if (asset.isReserved) {
            [_propsDataSource addObject:filter];
        } else {
            if (_propsDataSource.count > 0) {
                [_propsDataSource insertObject:filter atIndex:1];
            } else {
                [_propsDataSource insertObject:filter atIndex:0];
            }
        }
    }
    
    [self addNoneFaceSticker];
}

- (void)addNoneFaceSticker {
    for (NvFilterItem *item in _propsDataSource) {
        if ([item.cover isEqualToString:@"NvsFilterNone"])
            return;
    }
    NvFilterItem *item = [NvFilterItem new];
    item.builtinName = nil;
    item.package = nil;
    item.selected = NO;
    item.cover = @"NvsFilterNone";
    item.displayName = @"";
    [_propsDataSource insertObject:item atIndex:0];
}

- (BOOL)isFilterExist:(NSString *)uuid {
    for (NvCaptureFilterModel *item in _filterDataSource) {
        if ([item.packageId isEqualToString:uuid])
            return YES;
    }
    return NO;
}

- (BOOL)isFaceStickerExist:(NSString *)uuid {
    for (NvFilterItem *item in _propsDataSource) {
        if ([item.package isEqualToString:uuid])
            return YES;
    }
    return NO;
}

- (void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
    self.navigationController.navigationBar.hidden = NO;
}

#pragma mark 开始录制
- (void)startRecording{
    NSString *path = [VIDEO_PATH(@"Record") stringByAppendingPathComponent:[NSString stringWithFormat:@"%@.mp4", [NvUtils currentDateAndTime]]];
    NSMutableDictionary *config = [[NSMutableDictionary alloc] init];
    [_streamingContext startRecordingWithFx:path withFlags:0 withRecordConfigurations:config];
    [self.videoPathArray addObject:path];
}

#pragma mark 关闭录制
- (void)stopRecording{
    [_streamingContext stopRecording];
    if (_cuttentInteger == 0) {
        self.pngPath = [self.videoPathArray.lastObject stringByReplacingOccurrencesOfString:@"mp4" withString:@"png"];
        [self getScreenShotImageFromVideoPath:self.videoPathArray.lastObject handler:^(UIImage *image) {
            //            UIImageWriteToSavedPhotosAlbum(image, self, nil, nil);
            NSData *data = UIImagePNGRepresentation(image);
            [data writeToFile:self.pngPath atomically:YES];
            NSString *filePath = (NSString *)[self.videoPathArray lastObject];
            [self.videoPathArray removeLastObject];
            NSError *error;
            if (![[NSFileManager defaultManager] removeItemAtPath:filePath error:&error]){
                NSLog(@"删除文件失败, 错误: %@", error);
            }
            [self.videoPathArray addObject:self.pngPath];
            self.isHaveImage = YES;
            dispatch_async(dispatch_get_main_queue(), ^{
                self.picturePreview.image = image;
                [UIView animateWithDuration:0.3 animations:^{
                    self.picturePanelView.frame = CGRectMake(0, 0, SCREEN_WDITH, SCREANHEIGHT);
                }];
            });
        }];
    }else{
        PHAuthorizationStatus status = [PHPhotoLibrary authorizationStatus];
        if (status == PHAuthorizationStatusRestricted || status == PHAuthorizationStatusDenied)
        {
            if (!self.photoView) {
                [self tipView];
            }
            return;
        }
        if (self.photoView) {
            [self.photoView removeFromSuperview];
        }
        UISaveVideoAtPathToSavedPhotosAlbum(self.videoPathArray.lastObject, self, nil, nil);
    }
    //    UISaveVideoAtPathToSavedPhotosAlbum(
    //                                        self.videoPathArray.lastObject, self, @selector(video:didFinishSavingWithError:contextInfo:), nil);
}

- (void)tipView{
    self.photoView = [[NvTipsView alloc]initWithFrame:self.view.frame withPrompt:@"保存失败" describeTitle:@"您还没有允许相册访问权限" describeContent:nil buttonText:@"知道了" withCenter:YES];
    [_photoView.clickBtn addTarget:self action:@selector(knowClick:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:_photoView];
}

#pragma mark tipView按钮点击事件
- (void)knowClick:(UIButton *)sender{
    _photoView.hidden = YES;
}

#pragma mark 将拍摄的视频保存到本地相册
- (void)video:(NSString *)videoPath didFinishSavingWithError:(NSError *)error contextInfo:(void *)contextInfo {
    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"打包成功" message:@"已保存至相册" delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil, nil];
    [alert show];
}

#pragma mark 初始化美摄sdk
- (void)startupCapture{
    // 初始化美摄SDK
    self.streamingContext = [NvSDKUtils getSDKContext];
    if (!_streamingContext) {
        NSLog(@"初始化失败！");
        return;
    }

    // 设置回调接口
    _streamingContext.delegate = self;

    // 检查可用采集设备的数量
    if ([_streamingContext captureDeviceCount] == 0) {
        NSLog(@"没有可用于采集的设备！");
    }

    // 创建采集预览窗口并连接到摄像头采集次输出
    _liveWindowBack = [[NvsLiveWindow alloc] initWithFrame:CGRectMake(0, 0, self.view.width, self.view.height)];
    [self.view addSubview:_liveWindowBack];
    _liveWindow = [[NvsLiveWindow alloc] initWithFrame:CGRectMake(0, 0, self.view.width, self.view.height)];
    [self.view addSubview:_liveWindow];
    _curLiveWindow = _liveWindowBack;
    if (![_streamingContext connectCapturePreviewWithLiveWindow:_curLiveWindow]) {
        NSLog(@"连接预览窗口失败！");
    }
    _curLiveWindow = _liveWindow;
    if (![_streamingContext connectCapturePreviewWithLiveWindow:_curLiveWindow]) {
        NSLog(@"连接预览窗口失败！");
    }

    self.currentDeviceIndex = [self frontCameraDeviceIndex];
    if (![self startCapturePreview]) {
        NSLog(@"启动摄像头采集预览失败！");
    }
    
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(singleTap:)];
    tap.numberOfTapsRequired = 1;
    [_liveWindow addGestureRecognizer:tap];
    
    UITapGestureRecognizer *tap1 = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(singleTap:)];
    tap.numberOfTapsRequired = 1;
    [_liveWindowBack addGestureRecognizer:tap1];
    
    [self initARFace];
    
    [self addSubViews];
    [self addFilterView];
    [self addPropsView];
    [self addZoomView];
    [self addexposureView];
    [self initFocusView];
    [self addBeauty];
    [self configParameter];
    [self addPicturePreview];
}

- (void)initARFace {
#ifdef NV_AI_FU
    dispatch_once(&onceToken, ^{
        NSString *str = [[[NSBundle mainBundle] bundlePath] stringByAppendingPathComponent:@"NvFaceData.bundle"];
        
        [NvsFaceEffectV1 InitFaceEffectV1:str authPackage:&g_auth_package authSize:sizeof(g_auth_package)];
        [NvsFaceEffectV1 SetMaxFaces:2];
    });
    
    dispatch_async(dispatch_get_main_queue(), ^{
        //notify capture face effect init
        NSLog(@"AR Face Init complete!");
        
        self.arfaceVideoFx = [self->_streamingContext appendBuiltinCaptureVideoFx:@"Face Effect"];
        self.fxARFace = self.arfaceVideoFx;
        NSString *str1 = [[[NSBundle mainBundle] bundlePath] stringByAppendingPathComponent:@"NvBeautification.bundle"];
        [self.arfaceVideoFx setStringVal:@"Beautification Package" val:str1];
        [self.arfaceVideoFx setStringVal:@"Face Ornament" val:@""];
        [self.arfaceVideoFx setFloatVal:@"Face Shape Level" val:0];
        [self.arfaceVideoFx setMenuVal:@"Face Type" val:@""];
    });
#endif
}

#pragma mark 启动采集之后，初始化效果采集参数
- (void)configParameter{
    self.timeLabel.hidden = YES;
    self.deleteBtn.hidden = YES;
    self.finishBtn.hidden = YES;
    
    if (_currentDeviceIndex == [self frontCameraDeviceIndex]) {
        self.flashBtn.userInteractionEnabled = NO;
        self.flashBtn.alpha = 0.7;
    } else {
        self.flashBtn.userInteractionEnabled = YES;
        self.flashBtn.alpha = 1;
    }
    
    //给美颜美型视图配置默认数据
    if (!self.fx) {
        self.fx = [self.streamingContext appendBeautyCaptureVideoFx];
    }
    
    NSMutableArray *beautyArray = [NSMutableArray array];
    NSArray *beautyArray_1 = @[@"磨皮", @"美白", @"红润"];
    NSArray *beautyArray_2 = @[@"NvCaptureBeautyStrength", @"NvCaptureBeautyWhitening", @"NvCaptureBeautyReddening"];
    NSArray *beautyArray_3 = @[@"Strength", @"Whitening", @"Reddening"];
    for (int i = 0; i < beautyArray_1.count; i++) {
        NvBeautyTypeModel *beautyModel = [NvBeautyTypeModel new];
        beautyModel.name = beautyArray_1[i];
        beautyModel.coverImage = beautyArray_2[i];
        beautyModel.selected = NO;
        beautyModel.isOperation = NO;
        beautyModel.isBeauty = YES;
        beautyModel.fxName = beautyArray_3[i];
        beautyModel.value = [self.fx getFloatVal:beautyArray_3[i]];
        [self.beautyFxArray addObject:beautyModel];
        [beautyArray addObject:beautyModel];
    }
    [self.beautyView configBeautyArray:beautyArray];
    
    NSMutableArray *beautyByteArray = [NSMutableArray array];
    NSArray *beautyByteArray_1 = @[@"瘦脸", @"大眼", @"下巴", @"额头", @"瘦鼻", @"嘴型"];
    NSArray *beautyByteArray_2 = @[@"NvCaptureBeautyTypeFace", @"NvCaptureBeautyTypeEye", @"NvCaptureBeautyTypeChin", @"NvCaptureBeautyTypeForehead", @"NvCaptureBeautyTypeNose", @"NvCaptureBeautyTypeMouth"];
    NSArray *beautyByteArray_3 = @[@"Cheek Thinning", @"Eye Enlarging", @"Intensity Chin", @"Intensity Forhead", @"Intensity Nose", @"Intensity Mouth"];
    for (int i = 0; i < beautyByteArray_1.count; i++) {
        NvBeautyTypeModel *beautyByteModel = [NvBeautyTypeModel new];
        beautyByteModel.name = beautyByteArray_1[i];
        beautyByteModel.coverImage = beautyByteArray_2[i];
        beautyByteModel.selected = i == 0?YES:NO;
        beautyByteModel.isOperation = NO;
        beautyByteModel.isBeauty = NO;
        beautyByteModel.fxName = beautyByteArray_3[i];
        if ([beautyByteArray_1[i] isEqualToString:@"下巴"]) {
            beautyByteModel.value = 0.5;
        }else if ([beautyByteArray_1[i] isEqualToString:@"额头"]){
            beautyByteModel.value = 0.5;
        }else if ([beautyByteArray_1[i] isEqualToString:@"嘴型"]){
            beautyByteModel.value = 0.5;
        }else{
            beautyByteModel.value = 0;
        }
        [self.beautyTypeFxArray addObject:beautyByteModel];
        [beautyByteArray addObject:beautyByteModel];
    }
    [self.beautyView configBeautyByteArray:beautyByteArray];
    
    NvBeautyTypeModel *sharpenModel = [NvBeautyTypeModel new];
    sharpenModel.name = nil;
    sharpenModel.coverImage = @"NvCaptureBeautySharpen";
    sharpenModel.selected = [self.fx getBooleanVal:@"Default Sharpen Enabled"];
    sharpenModel.isOperation = NO;
    sharpenModel.isBeauty = YES;
    sharpenModel.fxName = @"Default Sharpen Enabled";
    [beautyArray addObject:sharpenModel];
    
    NvBeautyTypeModel *filterModel = [NvBeautyTypeModel new];
    filterModel.name = nil;
    filterModel.coverImage = @"NvCaptureBeautyFilter";
    filterModel.selected =  [self.fx getBooleanVal:@"Default Beauty Enabled"];
    filterModel.isOperation = NO;
    filterModel.isBeauty = YES;
    filterModel.fxName = @"Default Beauty Enabled";
    filterModel.value = [self.fx getFloatVal:@"Strength"];
    [beautyArray addObject:filterModel];
    
    self.isBeautyFilter = YES;//默认Default Beauty Enabled是yes
    
    [self.beautyView configBeautyFilter:filterModel withSharpen:sharpenModel];
    [self.streamingContext removeAllCaptureVideoFx];
    self.fx = nil;
}

#pragma mark NvsStreamingContextDelegate
- (void)didCaptureRecordingDurationUpdated:(int)captureDeviceIndex duration:(int64_t)duration{
    if (_cuttentInteger == 0) {
        if (duration >= 40000) {
            if (self.isHaveImage) {
                self.isHaveImage = NO;
                [self stopRecording];
            }
        }
    }else{
        self.lastDuration = duration;
        self.timeLabel.text = [NvUtils convertTimecode:self.duration + duration];
        if (duration >= NV_TIME_BASE) {
            self.shootingBtn.enabled = YES;
        }
    }
}

- (void)didCaptureDeviceCapsReady:(unsigned int)captureDeviceIndex{
    // 获取采集设备的能力描述
    self.capability = [_streamingContext getCaptureDeviceCapability:captureDeviceIndex];
    if (!self.capability){
        return;
    }
    
    [self.zoomView configMinimumValue:1 MaximumValue:self.capability.maxZoomFactor > 10 ? 10 : self.capability.maxZoomFactor];
    [self.exposureView configMinimumValue:-1 MaximumValue:1];
    self.zoomView.defaultValue = [_streamingContext getZoomFactor];
    self.exposureView.defaultValue = [_streamingContext getExposureBias];
    
    CGPoint point = CGPointMake(0.49*self.liveWindow.width, self.liveWindow.height / 2);
    if (self.capability.supportAutoFocus) {
        [_streamingContext startAutoFocus:point];
    }
    if (self.capability.supportAutoExposure) {  // 支持自动曝光则自动曝光
        [_streamingContext startAutoExposure:point];
    }
}

#pragma mark 添加变焦视图
- (void)addZoomView{
    self.zoomView = [[NvCapturePopupView alloc]initWithFrame:CGRectMake(0, SCREEN_HEIGTH, SCREEN_WDITH, 126 * SCREANSCALE) withType:CapturePopupTypeZoom];
    [self.view addSubview:_zoomView];
    __weak typeof(self)weakSelf = self;
    self.zoomView.ValueBlook = ^(float value) {
        [weakSelf.streamingContext setZoomFactor:value];
    };
}

#pragma mark 添加曝光视图
- (void)addexposureView{
    self.exposureView = [[NvCapturePopupView alloc]initWithFrame:CGRectMake(0, SCREEN_HEIGTH, SCREEN_WDITH, 126 * SCREANSCALE) withType:CapturePopupTypeExposure];
    [self.view addSubview:_exposureView];
    __weak typeof(self)weakSelf = self;
    self.exposureView.ValueBlook = ^(float value) {
        [weakSelf.streamingContext setExposureBias:value];
    };
}

#pragma mark 添加滤镜视图
- (void)addFilterView{
    self.filterView = [[NvCaptureFilterView alloc]initWithFrame:CGRectMake(0, SCREANHEIGHT, SCREANWIDTH, 173 * SCREANSCALE + INDICATOR)];
    self.filterView.delegate = self;
    [self.view addSubview:self.filterView];
}

#pragma mark 添加拍照预览视图
- (void)addPicturePreview{
    _picturePanelView = [[UIView alloc] initWithFrame:CGRectMake(0, SCREANHEIGHT, SCREANWIDTH, SCREANHEIGHT)];
    _picturePanelView.backgroundColor = UIColor.blackColor;
    [self.view addSubview:_picturePanelView];
    
    _picturePreview = [[UIImageView alloc]initWithFrame:CGRectMake(0, 0, _picturePanelView.frame.size.width, _picturePanelView.frame.size.height)];
    _picturePreview.contentMode = UIViewContentModeScaleAspectFit;
    [_picturePanelView addSubview:_picturePreview];
    
    UIButton *cancelBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [cancelBtn addTarget:self action:@selector(cancelBtn:) forControlEvents:UIControlEventTouchUpInside];
    [cancelBtn setImage:[NvUtils imageWithName:@"Nvback"] forState:UIControlStateNormal];
    [_picturePanelView addSubview:cancelBtn];
    
    UIButton *determineBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [determineBtn addTarget:self action:@selector(determineBtn:) forControlEvents:UIControlEventTouchUpInside];
    [determineBtn setImage:[NvUtils imageWithName:@"NvCaptureDetermine"] forState:UIControlStateNormal];
    [_picturePanelView addSubview:determineBtn];
    [cancelBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.picturePanelView.mas_top).offset(NV_STATUSBARHEIGHT);
        make.left.equalTo(self.picturePanelView.mas_left).offset(13 * SCREANSCALE);
    }];
    
    [determineBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.picturePanelView.mas_top).offset(NV_STATUSBARHEIGHT);
        make.right.equalTo(self.picturePanelView.mas_right).offset(-13 * SCREANSCALE);
    }];
}

#pragma mark 添加道具视图
- (void)addPropsView{
    _propsPanelView = [[UIView alloc] initWithFrame:CGRectMake(0, SCREEN_HEIGTH, SCREEN_WDITH, 123*SCREANSCALE)];
    _propsPanelView.backgroundColor = [UIColor nv_colorWithHexARGB:@"#99000000"];
    [self.view addSubview:_propsPanelView];
    
    UIButton *moreB = [UIButton buttonWithType:UIButtonTypeCustom];
    [moreB setImage:[NvUtils imageWithName:@"NvsFilterMore"] forState:UIControlStateNormal];
    moreB.frame = CGRectMake(13 * SCREANSCALE, 30 * SCREANSCALE, 35 * SCREANSCALE, 25 * SCREANSCALE);
    [_propsPanelView addSubview:moreB];
    [moreB addTarget:self action:@selector(moreClick:) forControlEvents:UIControlEventTouchUpInside];
    
    UILabel *moreL = [[UILabel alloc]initWithFrame:CGRectMake(18 * SCREANSCALE, moreB.frame.origin.y + moreB.frame.size.height + 10, 30 * SCREANSCALE, 21 * SCREANSCALE)];
    moreL.text = @"更多";
    moreL.textColor = [UIColor nv_colorWithHexARGB:@"#CCFFFFFF"];
    moreL.font = [NvUtils regularFontWithSize:11];
    [_propsPanelView addSubview:moreL];
    
    UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc] init];
    layout.scrollDirection = UICollectionViewScrollDirectionHorizontal;
    layout.itemSize = CGSizeMake(58*SCREANSCALE, 70*SCREANSCALE);
    layout.minimumLineSpacing = 10*SCREANSCALE;
    layout.minimumInteritemSpacing = 0;
    layout.sectionInset = UIEdgeInsetsMake(0, 16*SCREANSCALE, 0, 0);
    _propsCollectionView = [[UICollectionView alloc] initWithFrame:CGRectMake(60 * SCREANSCALE, 25*SCREANSCALE, SCREEN_WDITH - 60 * SCREANSCALE, 70*SCREANSCALE) collectionViewLayout:layout];
    _propsCollectionView.delegate = self;
    _propsCollectionView.dataSource = self;
    _propsCollectionView.backgroundColor = [UIColor clearColor];
    _propsCollectionView.showsHorizontalScrollIndicator = NO;
    [_propsPanelView addSubview:_propsCollectionView];
    [_propsCollectionView registerClass:[NvFilterCell class] forCellWithReuseIdentifier:@"NvPropsCell"];
}

#pragma mark 关闭退出
- (void)backBtnClick:(UIButton *)sender{
    [self.streamingContext removeAllCaptureVideoFx];
    [self.streamingContext setExposureBias:0.0];
    [self.streamingContext stop];
    [self.streamingContext clearCachedResources:NO];
    //    [NvsStreamingContext destroyInstance];
    [self.navigationController popViewControllerAnimated:YES];
}

#pragma mark 切换摄像头
- (void)deviceBtnClick:(UIButton *)sender{
    UIView *fromView;
    UIView *toView;
    if ([_curLiveWindow isEqual:_liveWindow]) {
        fromView = _liveWindow;
        toView = _liveWindowBack;
    } else {
        fromView = _liveWindowBack;
        toView = _liveWindow;
    }
    _curLiveWindow = (NvsLiveWindow *)toView;
    
    if (![_streamingContext connectCapturePreviewWithLiveWindow:_curLiveWindow]) {
        NSLog(@"连接预览窗口失败！");
    }
    
    if (_currentDeviceIndex == 0) {
        _currentDeviceIndex = 1;
    } else {
        _currentDeviceIndex = 0;
    }
    
    if (_currentDeviceIndex == [self frontCameraDeviceIndex]) {
        _flashBtn.alpha = 0.7;
        _flashBtn.userInteractionEnabled = NO;
        _flashBtn.selected = NO;
    } else {
        _flashBtn.alpha = 1;
        _flashBtn.userInteractionEnabled = YES;
    }
     [self.arfaceVideoFx setStringVal:@"Face Ornament" val:@""];
//    [self startCapturePreview];
    [UIView transitionFromView:fromView toView:toView duration:0.3 options:UIViewAnimationOptionTransitionFlipFromRight completion:^(BOOL finished) {
        [self.view sendSubviewToBack:self.curLiveWindow];
    }];
    if ([self startCapturePreview]) {
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.6 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            if (self->_currentPropsIndex != 0) {
                NvFilterItem *item = self->_propsDataSource[self->_currentPropsIndex];
                [self.arfaceVideoFx setStringVal:@"Face Ornament" val:item.package];
            }
        });
    }
}

#pragma mark 预览照片视图取消点击事件处理
- (void)cancelBtn:(UIButton *)sender{
    self.shootingBtn.enabled = YES;
    NSString *filePath = (NSString *)[self.videoPathArray lastObject];
    NSError *error;
    if (![[NSFileManager defaultManager] removeItemAtPath:filePath error:&error]){
        NSLog(@"删除文件失败, 错误: %@", error);
    }
    [self.videoPathArray removeLastObject];
    [UIView animateWithDuration:0.3 animations:^{
        self.picturePanelView.frame = CGRectMake(0, SCREEN_HEIGTH, SCREEN_WDITH, SCREANHEIGHT);
    }];
}

#pragma mark 预览照片视图确定点击事件处理
- (void)determineBtn:(UIButton *)sender{
    self.shootingBtn.enabled = YES;
    self.videoCount.hidden = NO;
    self.timeLabel.hidden = NO;
    self.finishBtn.hidden = NO;
    self.deleteBtn.hidden = NO;
    UIImageWriteToSavedPhotosAlbum(self.picturePreview.image, self, nil, nil);
    self.lastDuration = 4 * NV_TIME_BASE;
    self.duration = self.duration + self.lastDuration;
    self.videoCount.text = [NSString stringWithFormat:@"%lu",(unsigned long)_videoPathArray.count];
    self.timeLabel.text = [NvUtils convertTimecode:self.duration];
    self.timeLabel.textColor = UIColor.whiteColor;
    [self.durationArray addObject:[NSNumber numberWithLongLong:self.lastDuration]];
    [UIView animateWithDuration:0.3 animations:^{
        self.picturePanelView.frame = CGRectMake(0, SCREEN_HEIGTH, SCREEN_WDITH, SCREANHEIGHT);
    }];
}

#pragma mark 闪光灯开关
- (void)flashBtnClick:(UIButton *)sender{
    if ([_streamingContext getCaptureDeviceCapability:_currentDeviceIndex].supportFlash) {
        [_streamingContext toggleFlash:![_streamingContext isFlashOn]];
        _flashBtn.selected = sender.isSelected ? NO : YES;
    }
}

#pragma mark 变焦按钮点击
- (void)zoomBtnClick:(UIButton *)sender{
    self.clickState = YES;
    [self faceHiddenBtn:YES];
    self.currentView = self.zoomView;
    [UIView animateWithDuration:0.1 animations:^{
        self.zoomView.frame = CGRectMake(0, SCREEN_HEIGTH - 126*SCREANSCALE, SCREEN_WDITH, 126 * SCREANSCALE);
    }];
}

#pragma mark 曝光按钮点击
- (void)exposureBtnClick:(UIButton *)sender{
    self.clickState = YES;
    [self faceHiddenBtn:YES];
    self.currentView = self.exposureView;
    [UIView animateWithDuration:0.1 animations:^{
        self.exposureView.frame = CGRectMake(0, SCREEN_HEIGTH - 126*SCREANSCALE, SCREEN_WDITH, 126 * SCREANSCALE);
    }];
}

#pragma mark 美颜开关
- (void)beautyBtnClick:(UIButton *)sender{
    _beautyBtn.selected = _beautyBtn.selected?NO:YES;
    self.clickState = YES;
    [self faceHiddenBtn:YES];
    self.currentView = self.beautyView;
    [UIView animateWithDuration:0.1 animations:^{
        if (KIsiPhoneX) {
            self.beautyView.frame = CGRectMake(0, SCREEN_HEIGTH - 264*SCREANSCALE - 34, SCREEN_WDITH, 264 * SCREANSCALE + 34);
        }else{
            self.beautyView.frame = CGRectMake(0, SCREEN_HEIGTH - 264*SCREANSCALE, SCREEN_WDITH, 264 * SCREANSCALE);
        }
        
    }];
}

#pragma mark 滤镜按钮点击
- (void)filterBtnClick:(UIButton *)sender{
    [self updateFilters];
    [self.filterView configDataSource:self.filterDataSource];
    self.clickState = YES;
    [self faceHiddenBtn:YES];
    self.currentView = self.filterView;
    [UIView animateWithDuration:0.1 animations:^{
        self.filterView.frame = CGRectMake(0, SCREEN_HEIGTH - self.filterView.frame.size.height, SCREEN_WDITH, self.filterView.frame.size.height);
    }];
}

#pragma mark 道具按钮点击
- (void)propsBtnClick:(UIButton *)sender{
#ifdef NV_AI_FU
        [self updateFaceStickers];
        [_propsCollectionView reloadData];
        self.clickState = YES;
        [self faceHiddenBtn:YES];
        self.currentView = self.propsPanelView;
        [UIView animateWithDuration:0.1 animations:^{
            self.propsPanelView.frame = CGRectMake(0, SCREEN_HEIGTH - self.propsPanelView.frame.size.height, SCREEN_WDITH, self.propsPanelView.frame.size.height);
        }];
#else
        [self showTip];
#endif
    
}

#pragma mark 拍摄按钮点击
- (void)shootingBtnClick:(UIButton *)sender{
    if (_cuttentInteger == 0) {
        self.shootingBtn.enabled = NO;
        self.isHaveImage = YES;
        [self startRecording];
    }else{
        if (sender.selected) {
            sender.selected = NO;
            [self faceHiddenBtn:NO];
            [self stopRecording];
            self.videoCount.text = [NSString stringWithFormat:@"%lu",(unsigned long)_videoPathArray.count];
            self.timeLabel.textColor = UIColor.whiteColor;
            self.videoCount.hidden = NO;
            self.duration = self.duration + self.lastDuration;
            [self.durationArray addObject:[NSNumber numberWithLongLong:self.lastDuration]];
        }else{
            self.timeLabel.textColor = UIColor.redColor;
            self.videoCount.hidden = YES;
            sender.selected = YES;
            [self faceHiddenBtn:YES];
            self.shootingBtn.hidden = NO;
            self.timeLabel.hidden = NO;
            self.shootingBtn.enabled = NO;
            [self startRecording];
        }
    }
}

#pragma mark 拍照相关
- (void)getScreenShotImageFromVideoPath:(NSString *)filePath handler:(void(^)(UIImage* image))handler{
    
    //视频路径URL
    NSURL *fileURL = [NSURL fileURLWithPath:filePath];
    
    AVURLAsset *asset = [[AVURLAsset alloc] initWithURL:fileURL options:nil];
    
    AVAssetImageGenerator *gen = [[AVAssetImageGenerator alloc] initWithAsset:asset];
    
    gen.appliesPreferredTrackTransform = YES;
    
    CMTime time = CMTimeMakeWithSeconds(0.0, 600);
    [gen generateCGImagesAsynchronouslyForTimes:@[[NSValue valueWithCMTime:time]] completionHandler:^(CMTime requestedTime, CGImageRef  _Nullable image, CMTime actualTime, AVAssetImageGeneratorResult result, NSError * _Nullable error) {
        handler([UIImage imageWithCGImage:image]);
    }];
    
}

#pragma mark 删除按钮点击
- (void)deleteBtnBtnClick:(UIButton *)sender{
    NSString *filePath = (NSString *)[_videoPathArray lastObject];
    [_videoPathArray removeLastObject];
    NSError *error;
    if (![[NSFileManager defaultManager] removeItemAtPath:filePath error:&error]){
         NSLog(@"删除文件失败, 错误: %@", error);
    }
    if (_videoPathArray.count == 0) {
        self.videoCount.text = @"";
        self.timeLabel.text = @"00:00";
        self.timeLabel.hidden = YES;
        self.deleteBtn.hidden = YES;
        self.finishBtn.hidden = YES;
        self.duration = 0;
    }else{
        self.videoCount.text = [NSString stringWithFormat:@"%lu",(unsigned long)_videoPathArray.count];
        self.duration = self.duration - [[_durationArray lastObject] longLongValue];
        self.timeLabel.text = [NvUtils convertTimecode:self.duration];
    }
    
}

#pragma mark 完成按钮点击
- (void)finishBtnBtnClick:(UIButton *)sender{
    //路径数组 self.videoPathArray
    NvEditViewController *vc  = [[NvEditViewController alloc]init];
    AVURLAsset*audioAsset=[AVURLAsset URLAssetWithURL:[NSURL fileURLWithPath:self.videoPathArray.firstObject] options:nil];
    AVAssetTrack *track = [[audioAsset tracksWithMediaType:AVMediaTypeVideo] firstObject];
    CGSize dimensions = CGSizeApplyAffineTransform(track.naturalSize, track.preferredTransform);
    if (dimensions.width > dimensions.height) {
        vc.editMode = NvEditMode16v9;
    }else{
        vc.editMode = NvEditMode9v16;
    }
    vc.selectPath = self.videoPathArray;
    vc.isFromAlbum = NO;
    [self.navigationController pushViewController:vc animated:YES];
}

#pragma mark 获取前置摄像头设备索引
- (unsigned int)frontCameraDeviceIndex {
    for (unsigned int i = 0; i < _streamingContext.captureDeviceCount; i++) {
        if (![_streamingContext isCaptureDeviceBackFacing:i])
            return i;
    }
    return _streamingContext.captureDeviceCount - 1;
}


#pragma mark 启动摄像头采集预览
- (BOOL)startCapturePreview {
    NSNumber *num = NV_UserInfo(@"NvRecordResolution");
    NvsVideoCaptureResolutionGrade captureResGrade = [num intValue] == 1080? NvsVideoCaptureResolutionGradeHigh:NvsVideoCaptureResolutionGradeMedium;
    if (![_streamingContext isCaptureDeviceBackFacing:_currentDeviceIndex]){
        captureResGrade = NvsVideoCaptureResolutionGradeHigh;
    }
    NSLog(@"%d",captureResGrade);
    return [_streamingContext startCapturePreview:_currentDeviceIndex videoResGrade:captureResGrade flags:NvsStreamingEngineCaptureFlag_CaptureBuddyHostVideoFrame | NvsStreamingEngineCaptureFlag_StrictPreviewVideoSize aspectRatio:nil];
}

#pragma mark 点击隐藏界面按钮
- (void)faceHiddenBtn:(BOOL)hidden{
    self.filterBtn.hidden = hidden;
    self.deviceBtn.hidden = hidden;
    self.flashBtn.hidden = hidden;
    self.zoomBtn.hidden = hidden;
    self.exposureBtn.hidden = hidden;
    self.beautyBtn.hidden = hidden;
    self.propsBtn.hidden = hidden;
    self.backBtn.hidden = hidden;
    self.shootingBtn.hidden = hidden;
    self.timeLabel.hidden = hidden;
    self.deleteBtn.hidden = hidden;
    self.finishBtn.hidden = hidden;
    self.psTitleCollectionView.hidden = hidden;
    self.redView.hidden = hidden;
}

#pragma mark 点击空白显示界面按钮
- (void)singleTap:(UITapGestureRecognizer *)recognizer {
    if (self.clickState) {
        self.clickState = NO;
        [self faceHiddenBtn:NO];
        [UIView animateWithDuration:0.1 animations:^{
            self.currentView.frame = CGRectMake(0, SCREEN_HEIGTH, SCREEN_WDITH, self.currentView.frame.size.height);
        }];
        if (_videoPathArray.count == 0) {
            self.timeLabel.hidden = YES;
            self.deleteBtn.hidden = YES;
            self.finishBtn.hidden = YES;
        }else{
            self.timeLabel.hidden = NO;
            self.deleteBtn.hidden = NO;
            self.finishBtn.hidden = NO;
        }
    }else{
        CGPoint point = [recognizer locationInView:_curLiveWindow];
        if (point.x >= SCREEN_WDITH - 70 * SCREANSCALE || point.y >= SCREEN_HEIGTH - 190 * SCREANSCALE){
            return;
        }
        if (self.capability.supportAutoFocus) {
            [_streamingContext startAutoFocus:point];
            [self animateFocusView:point];
        }
        if (self.capability.supportAutoExposure) {
            [_streamingContext startAutoExposure:point];
            [self animateFocusView:point];
        }
        
    }
}

#pragma mark 添加子视图
- (void)addSubViews{
    // 初始化UI
    self.backBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [self.backBtn setImage:[NvUtils imageWithName:@"Nvback"] forState:UIControlStateNormal];
    [self.backBtn addTarget:self action:@selector(backBtnClick:) forControlEvents:UIControlEventTouchUpInside];
    
    self.deviceBtn = [NvGraphicBtn buttonWithType:UIButtonTypeCustom withTitle:@"切换" withImageNormal:@"Nvdevice" withImageSelected:nil];
    [self.deviceBtn addTarget:self action:@selector(deviceBtnClick:) forControlEvents:UIControlEventTouchUpInside];
    
    self.flashBtn = [NvGraphicBtn buttonWithType:UIButtonTypeCustom withTitle:@"补光" withImageNormal:@"Nvflash_off" withImageSelected:@"Nvflash_on"];
    [self.flashBtn addTarget:self action:@selector(flashBtnClick:) forControlEvents:UIControlEventTouchUpInside];
    
    self.zoomBtn = [NvGraphicBtn buttonWithType:UIButtonTypeCustom withTitle:@"变焦" withImageNormal:@"Nvzoom" withImageSelected:nil];
    [self.zoomBtn addTarget:self action:@selector(zoomBtnClick:) forControlEvents:UIControlEventTouchUpInside];
    
    self.exposureBtn = [NvGraphicBtn buttonWithType:UIButtonTypeCustom withTitle:@"曝光" withImageNormal:@"Nvexposure" withImageSelected:nil];
    [self.exposureBtn addTarget:self action:@selector(exposureBtnClick:) forControlEvents:UIControlEventTouchUpInside];
    
    self.beautyBtn = [NvGraphicBtn buttonWithType:UIButtonTypeCustom withTitle:@"美颜" withImageNormal:@"Nvbeauty" withImageSelected:nil];
    [self.beautyBtn addTarget:self action:@selector(beautyBtnClick:) forControlEvents:UIControlEventTouchUpInside];
    
    self.filterBtn = [NvGraphicBtn buttonWithType:UIButtonTypeCustom withTitle:@"滤镜" withImageNormal:@"Nvfilter" withImageSelected:nil];
    [self.filterBtn addTarget:self action:@selector(filterBtnClick:) forControlEvents:UIControlEventTouchUpInside];
    
    self.propsBtn = [NvGraphicBtn buttonWithType:UIButtonTypeCustom withTitle:@"道具" withImageNormal:@"Nvprops" withImageSelected:nil];
    [self.propsBtn addTarget:self action:@selector(propsBtnClick:) forControlEvents:UIControlEventTouchUpInside];
    
    UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc] init];
    layout.scrollDirection = UICollectionViewScrollDirectionHorizontal;
    layout.itemSize = CGSizeMake(60*SCREANSCALE, 30*SCREANSCALE);
    layout.minimumLineSpacing = 0;
    layout.minimumInteritemSpacing = 0;
    self.psTitleCollectionView = [[UICollectionView alloc]initWithFrame:CGRectMake(0, 0, 0, 0) collectionViewLayout:layout];
    self.psTitleCollectionView.backgroundColor = UIColor.clearColor;
    self.psTitleCollectionView.delegate = self;
    self.psTitleCollectionView.dataSource = self;
    [self.psTitleCollectionView registerClass:[NvPsTitleCollectionViewCell class] forCellWithReuseIdentifier:@"NvpsTitleCell"];
    
    self.redView = [[UIView alloc]init];
    self.redView.backgroundColor = UIColor.redColor;
    self.redView.layer.cornerRadius = 5/2.0;
    self.redView.layer.masksToBounds = YES;
    
    self.shootingBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [self.shootingBtn setImage:[NvUtils imageWithName:@"Nvshooting"] forState:UIControlStateNormal];
    [self.shootingBtn setImage:[NvUtils imageWithName:@"Nvsuspended"] forState:UIControlStateSelected];
    [self.shootingBtn addTarget:self action:@selector(shootingBtnClick:) forControlEvents:UIControlEventTouchUpInside];
    
    self.deleteBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [self.deleteBtn setImage:[NvUtils imageWithName:@"Nvdelete"] forState:UIControlStateNormal];
    [self.deleteBtn addTarget:self action:@selector(deleteBtnBtnClick:) forControlEvents:UIControlEventTouchUpInside];
    
    self.finishBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [self.finishBtn setImage:[NvUtils imageWithName:@"Nvfinish"] forState:UIControlStateNormal];
    [self.finishBtn addTarget:self action:@selector(finishBtnBtnClick:) forControlEvents:UIControlEventTouchUpInside];
    self.timeLabel = [UILabel new];
    self.timeLabel.text = @"00:00";
    self.timeLabel.textColor = [UIColor nv_colorWithHexRGB:@"#D0021B"];
    self.timeLabel.font = [NvUtils fontWithSize:12];
    
    self.videoCount = [UILabel new];
    self.videoCount.userInteractionEnabled = NO;
    self.videoCount.font = [NvUtils fontWithSize:12];
    self.videoCount.textColor = UIColor.whiteColor;
    
    [self.view addSubview:self.backBtn];
    [self.view addSubview:self.deviceBtn];
    [self.view addSubview:self.flashBtn];
    [self.view addSubview:self.zoomBtn];
    [self.view addSubview:self.exposureBtn];
    [self.view addSubview:self.beautyBtn];
    [self.view addSubview:self.filterBtn];
    [self.view addSubview:self.propsBtn];
    [self.view addSubview:self.shootingBtn];
    [self.view addSubview:self.redView];
    [self.view addSubview:self.psTitleCollectionView];
    [self.view addSubview:self.deleteBtn];
    [self.view addSubview:self.finishBtn];
    [self.view addSubview:self.timeLabel];
    [self.shootingBtn addSubview:self.videoCount];
    
    [self.backBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.view).offset(NV_STATUSBARHEIGHT);
        make.left.equalTo(self.view).offset(13 * SCREANSCALE);
        make.width.offset(33 * SCREANSCALE);
        make.height.offset(33 * SCREANSCALE);
    }];
    
    [self.deviceBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.view).offset(NV_STATUSBARHEIGHT);
        make.right.equalTo(self.view).offset(- 13 * SCREANSCALE);
        make.width.offset(33 * SCREANSCALE);
    }];
    
    [self.flashBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.deviceBtn.mas_bottom).offset(10 * SCREANSCALE);
        make.leading.equalTo(self.deviceBtn.mas_leading);
        make.width.equalTo(self.deviceBtn.mas_width);
    }];
    
    [self.zoomBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.flashBtn.mas_bottom).offset(10 * SCREANSCALE);
        make.leading.equalTo(self.deviceBtn.mas_leading);
        make.width.equalTo(self.deviceBtn.mas_width);
    }];
    
    [self.exposureBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.zoomBtn.mas_bottom).offset(10 * SCREANSCALE);
        make.leading.equalTo(self.deviceBtn.mas_leading);
        make.width.equalTo(self.deviceBtn.mas_width);
    }];
    
    [self.beautyBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.exposureBtn.mas_bottom).offset(10 * SCREANSCALE);
        make.leading.equalTo(self.deviceBtn.mas_leading);
        make.width.equalTo(self.deviceBtn.mas_width);
    }];
    
    [self.filterBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.beautyBtn.mas_bottom).offset(10 * SCREANSCALE);
        make.leading.equalTo(self.deviceBtn.mas_leading);
        make.width.equalTo(self.deviceBtn.mas_width);
    }];
    
    [self.propsBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.filterBtn.mas_bottom).offset(10 * SCREANSCALE);
        make.leading.equalTo(self.deviceBtn.mas_leading);
        make.width.equalTo(self.deviceBtn.mas_width);
    }];
    
    [self.shootingBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.bottom.equalTo(self.view.mas_bottom).offset(- 20 * SCREANSCALE);
        make.centerX.equalTo(self.view.mas_centerX);
        make.width.offset(64 * SCREANSCALE);
        make.height.offset(64 * SCREANSCALE);
    }];
    
    [self.redView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.bottom.equalTo(self.shootingBtn.mas_top).offset(-5);
        make.centerX.equalTo(self.view.mas_centerX);
        make.width.offset(5 * SCREANSCALE);
        make.height.offset(5 * SCREANSCALE);
    }];
    
    [self.psTitleCollectionView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.bottom.equalTo(self.redView.mas_top).offset(-1);
        make.centerX.equalTo(self.view.mas_centerX);
        make.height.offset(30 * SCREANSCALE);
        make.width.offset(180  *SCREANSCALE);
    }];
    
    [self.deleteBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.equalTo(self.shootingBtn.mas_left).offset(- 56 * SCREANSCALE);
        make.centerY.equalTo(self.shootingBtn.mas_centerY);
        make.width.offset(48 * SCREANSCALE);
        make.height.offset(33 * SCREANSCALE);
    }];
    
    [self.finishBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.shootingBtn.mas_right).offset(56 * SCREANSCALE);
        make.centerY.equalTo(self.shootingBtn.mas_centerY);
        make.width.offset(40 * SCREANSCALE);
        make.height.offset(40 * SCREANSCALE);
    }];
    
    [self.timeLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(self.view.mas_centerX);
        make.centerY.equalTo(self.backBtn.mas_centerY);
    }];
    
    [self.videoCount mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(self.shootingBtn.mas_centerX);
        make.centerY.equalTo(self.shootingBtn.mas_centerY);
    }];
}

#pragma mark 更多按钮点击
- (void)moreClick:(UIButton *)sender{
    NvMoreFilterViewController *vc = [[NvMoreFilterViewController alloc]init];
    vc.type = ASSET_FACE1_STICKER;
    vc.isCapture = YES;
    [self.navigationController pushViewController:vc animated:YES];
}


#pragma mark - NvCaptureFilterViewDelegate
- (void)NvCaptureFilterView:(NvCaptureFilterView *)view withModel:(NvCaptureFilterModel *)model{
    self.currentFilterModel = model;
    if (_fxFilter) {
        [_streamingContext removeCaptureVideoFx:_fxFilter.index];
        _fxFilter = nil;
    }
    if (![model.displayName isEqualToString:@"无"]) {
        if (model.builtinName) {
            _fxFilter = [_streamingContext appendBuiltinCaptureVideoFx:model.builtinName];
            if ([model.builtinName isEqualToString:@"Cartoon"]) {
                [_fxFilter setBooleanVal:@"Stroke Only" val:model.strokeOnly];
                [_fxFilter setBooleanVal:@"Grayscale" val:model.grayscale];
                if (self.beautyView.beautySwitch.isSelected) {
                    [self switchAction:self.beautyView.beautySwitch];
                }
            }
        } else if (model.packageId) {
            _fxFilter = [_streamingContext appendPackagedCaptureVideoFx:model.packageId];
        }
    }
}

- (void)NvCaptureFilterView:(NvCaptureFilterView *)view sliderValueChanged:(UISlider *)slider{
    [_fxFilter setFilterIntensity:slider.value];
}

- (void)NvCaptureFilterView:(NvCaptureFilterView *)view moreClick:(UIButton *)sender{
    NvMoreFilterViewController *vc = [[NvMoreFilterViewController alloc]init];
    vc.type = ASSET_FILTER;
    vc.isCapture = YES;
    [self.navigationController pushViewController:vc animated:YES];
}

#pragma mark - UICollectionViewDataSource
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    if (collectionView == _psTitleCollectionView){
        return _psTitleArray.count;
    }
    return _propsDataSource.count;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    if (collectionView == _psTitleCollectionView){
        NvPsTitleCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"NvpsTitleCell" forIndexPath:indexPath];
        [cell renderCellWithString:self.psTitleArray[indexPath.item]];
        return cell;
    }
    NvFilterCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"NvPropsCell" forIndexPath:indexPath];
    [cell renderCellWithItem:_propsDataSource[indexPath.item]];
    return cell;
}

#pragma mark - UICollectionViewDelegate
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
    if (collectionView == _psTitleCollectionView){
        _cuttentInteger = indexPath.item;
        for (NvPsTitleModel *model in self.psTitleArray) {
            model.selected = NO;
        }
        NvPsTitleModel *seletedModel = self.psTitleArray[_cuttentInteger];
        seletedModel.selected = YES;
        [_psTitleCollectionView reloadData];
        
        if (_cuttentInteger == 0) {
            [_psTitleCollectionView setContentOffset:CGPointMake(-60 * SCREANSCALE, 0) animated:YES];
        }else{
            [_psTitleCollectionView setContentOffset:CGPointMake(0, 0) animated:YES];
        }

    }else{
        for (NvFilterItem *item in _propsDataSource) {
            item.selected = NO;
        }
        _currentPropsIndex = (unsigned int)indexPath.row;
        NvFilterItem *item = _propsDataSource[indexPath.row];
        item.selected = YES;
        [_propsCollectionView reloadData];
        if (indexPath.item != 0) {
            [self.arfaceVideoFx setStringVal:@"Face Ornament" val:item.package];
        }else{
            [self.arfaceVideoFx setStringVal:@"Face Ornament" val:@""];
        }
    }
}

#pragma mark 添加美颜视图
- (void)addBeauty{
    self.beautyView = [[NvBeautyView alloc]initWithFrame:CGRectMake(0, SCREEN_HEIGTH, SCREEN_WDITH, 264 * SCREANSCALE)];
    self.beautyView.delegate = self;
    self.beautyView.hiddenBool = YES;
    [self.beautyView.beautyBtn addTarget:self action:@selector(beautyClick:) forControlEvents:UIControlEventTouchUpInside];
    [self.beautyView.beautyTypeBtn addTarget:self action:@selector(beautyClick:) forControlEvents:UIControlEventTouchUpInside];
    [self.beautyView.beautySwitch addTarget:self action:@selector(switchAction:) forControlEvents:UIControlEventTouchUpInside];
#ifdef NV_AI_FU
    [self.beautyView.beautyTypeSwitch addTarget:self action:@selector(switchAction:) forControlEvents:UIControlEventTouchUpInside];
#else
    [self.beautyView.beautyTypeSwitch addTarget:self action:@selector(switchActionShowToast:) forControlEvents:UIControlEventTouchUpInside];
#endif
    [_streamingContext removeAllCaptureVideoFx];
    [self.beautyView editBool:NO withType:YES];
    [self.beautyView editBool:NO withType:NO];
    [self.view addSubview:self.beautyView];
}

#pragma mark NvBeautyViewDelegate
- (void)nvBeautyView:(NvBeautyView *)beautyView withModel:(NvBeautyTypeModel *)model withState:(BOOL)state{
    if (state) {
        NvBeautyTypeModel *model2;
        if (model.isBeauty) {
            if ([model.fxName isEqualToString:@"Default Beauty Enabled"]) {
                [self.fx setBooleanVal:model.fxName val:model.selected];
                [self.fx setFloatVal:@"Default Intensity" val:model.value];
                if (self.tipLabel) {
                    [self.tipLabel removeFromSuperview];
                    self.tipLabel = nil;
                }
                if (self.isBeautyFilter != model.selected) {
                    self.isBeautyFilter = model.selected;
                    self.tipLabel = [[UILabel alloc]init];
                    self.tipLabel.backgroundColor = UIColor.clearColor;
                    self.tipLabel.textColor = UIColor.whiteColor;
                    self.tipLabel.font = [NvUtils fontWithSize:16];
                    [self.view addSubview:self.tipLabel];
                    if (model.selected) {
                        self.tipLabel.text = @" • 美颜滤镜开启";
                    }else{
                        self.tipLabel.text = @" • 美颜滤镜关闭";
                    }
                    [self.tipLabel mas_makeConstraints:^(MASConstraintMaker *make) {
                        make.top.equalTo(self.view.mas_top).offset(231 * SCREANSCALE);
                        make.centerX.equalTo(self.view.mas_centerX);
                    }];
                    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                        [self.tipLabel removeFromSuperview];
                        self.tipLabel = nil;
                    });
                }
            }else if ([model.fxName isEqualToString:@"Default Sharpen Enabled"]){
                [self.fx setBooleanVal:model.fxName val:model.selected];
                if (self.tipLabel) {
                    [self.tipLabel removeFromSuperview];
                    self.tipLabel = nil;
                }
                self.tipLabel = [[UILabel alloc]init];
                self.tipLabel.backgroundColor = UIColor.clearColor;
                self.tipLabel.textColor = UIColor.whiteColor;
                self.tipLabel.font = [NvUtils fontWithSize:16];
                [self.view addSubview:self.tipLabel];
                if (model.selected) {
                    self.tipLabel.text = @" • 锐度开启";
                }else{
                    self.tipLabel.text = @" • 锐度关闭";
                }
                
                [self.tipLabel mas_makeConstraints:^(MASConstraintMaker *make) {
                    make.top.equalTo(self.view.mas_top).offset(231 * SCREANSCALE);
                    make.centerX.equalTo(self.view.mas_centerX);
                }];
                dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                    [self.tipLabel removeFromSuperview];
                    self.tipLabel = nil;
                });
            }
            for (NvBeautyTypeModel *model1 in self.beautyFxArray) {
                if ([model1.fxName isEqualToString:model.fxName]) {
                    model2 = model1;
                    break;
                }
            }
        }else{
            for (NvBeautyTypeModel *model1 in self.beautyTypeFxArray) {
                if ([model1.fxName isEqualToString:model.fxName]) {
                    model2 = model1;
                    break;
                }
            }
        }
        model2 = model;
    }else{
        if (model.isBeauty) {
            if ([model.fxName isEqualToString:@"Default Beauty Enabled"]) {
                [self.fx setBooleanVal:model.fxName val:model.selected];
                [self.fx setFloatVal:@"Default Intensity" val:model.value];
            }else if ([model.fxName isEqualToString:@"Default Sharpen Enabled"]){
                [self.fx setBooleanVal:model.fxName val:model.selected];
            }else{
                [self.fx setFloatVal:model.fxName val:model.value];
            }
        }else{
            [self.fxARFace setFloatVal:model.fxName val:model.value];
        }
    }
}

- (void)nvBeautyView:(NvBeautyView *)beautyView withModelArray:(NSMutableArray *)array{
    for (NvBeautyTypeModel *model in array) {
        [self.fxARFace setFloatVal:model.fxName val:model.value];
    }
}

#pragma mark 美颜视图，美颜按钮点击事件
- (void)beautyClick:(UIButton *)sender{
    if ([sender.titleLabel.text isEqualToString:@"美颜"]) {
        self.beautyView.hiddenBool = YES;
    }else{
        self.beautyView.hiddenBool = NO;
    }
}

#pragma mark 懒加载权限视图
- (NvTipsView *)permissions{
    if (!_permissions)
    {
        _permissions = [[NvTipsView alloc]initWithFrame:self.view.frame withPrompt:@"提示" describeTitle:@"需要打开摄像头和麦克风权限 请在手机设置中进行允许" describeContent:nil buttonText:@"知道了" withCenter:YES];
        [_permissions.clickBtn addTarget:self action:@selector(knowClick) forControlEvents:UIControlEventTouchUpInside];
    }
    return _permissions;
}

#pragma mark 权限按钮点击事件
- (void)knowClick{
    [_permissions removeFromSuperview];
    [self.navigationController popViewControllerAnimated:YES];
}

#pragma mark 添加手动对焦视图
- (void)initFocusView{
    self.focusView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 50, 50)];
    self.focusView.alpha = 0;
    [_focusView setImage:[NvUtils imageWithName:@"NvsCaptureFocus"]];
    [self.view addSubview:self.focusView];
}

#pragma mark 给手动对焦视图添加动画
- (void)animateFocusView:(CGPoint)currentPoint{
    self.focusView.center = currentPoint;
    
    CAAnimationGroup *group = [CAAnimationGroup animation];
    group.duration = 0.8;
    
    CABasicAnimation *alphaAnimation = [CABasicAnimation animationWithKeyPath:@"opacity"];
    alphaAnimation.fromValue = @1;
    alphaAnimation.toValue   = @1;
    alphaAnimation.repeatCount = 1;
    alphaAnimation.duration = .8;
    
    CABasicAnimation *focusAnimation = [CABasicAnimation animationWithKeyPath:@"transform.scale"];
    focusAnimation.fromValue = @1.7;
    focusAnimation.toValue   = @1;
    focusAnimation.repeatCount = 1;
    focusAnimation.duration = .3;
    
    CABasicAnimation *focusAnimation1 = [CABasicAnimation animationWithKeyPath:@"transform.scale"];
    focusAnimation1.fromValue = @1;
    focusAnimation1.toValue   = @1;
    focusAnimation1.repeatCount = 1;
    focusAnimation1.beginTime = 0.3;
    focusAnimation1.duration = 0.5;
    
    [group setAnimations:@[alphaAnimation,focusAnimation,focusAnimation1]];
    [self.focusView.layer addAnimation:group forKey:@"transform.scale"];
}

#pragma mark 美颜和美型按钮切换事件处理
- (void)switchAction:(NvSwitchView* )sender{
    if (sender.selected) {
        
        sender.backgroundColor = [UIColor nv_colorWithHexRGB:@"#4E5253"];
        sender.sliderView.backgroundColor = [UIColor nv_colorWithHexRGB:@"#DBDCDC"];
        sender.selected = NO;
        [UIView animateWithDuration:0.1 animations:^{
            sender.sliderView.frame = CGRectMake(2, 2, sender.sliderView.frame.size.width, sender.sliderView.frame.size.height);
        }];
        [self.beautyView editBool:NO withType:sender.tag == 1000?YES:NO];
        int count = [_streamingContext getCaptureVideoFxCount];
        for(int i=0;i<count;i++) {
            NvsCaptureVideoFx *fx = [_streamingContext getCaptureVideoFxByIndex:i];
            if (sender.tag == 1000) {
                if([fx isEqual:self.fx]) {
                    [_streamingContext removeCaptureVideoFx:i];
                    self.fx = nil;
                    break;
                }
            }else{
                if([fx isEqual:self.fxARFace]) {
                    [self.arfaceVideoFx setFloatVal:@"Face Shape Level" val:0];
                    [self.arfaceVideoFx setMenuVal:@"Face Type" val:@""];
                    break;
                }
            }
        }

    }else {
        sender.backgroundColor = [UIColor nv_colorWithHexRGB:@"#4A90E2"];
        sender.sliderView.backgroundColor = [UIColor nv_colorWithHexRGB:@"#D9E8FB"];
        sender.selected = YES;
        [UIView animateWithDuration:0.1 animations:^{
            sender.sliderView.frame = CGRectMake(sender.sliderView.frame.size.width, 2,sender.sliderView.frame.size.width, sender.sliderView.frame.size.height);
        }];
        [self.beautyView editBool:YES withType:sender.tag == 1000?YES:NO];
        if (sender.tag == 1000) {
            if (!self.fx) {
                self.fx = [self.streamingContext appendBeautyCaptureVideoFx];
            }
            if (self.currentFilterModel.builtinName && [self.currentFilterModel.builtinName isEqualToString:@"Cartoon"]) {
                for (NvCaptureFilterModel *item in self.filterDataSource) {
                    item.selected = NO;
                }
                NvCaptureFilterModel *item = self.filterDataSource[0];
                item.selected = YES;
                [self.filterView updateDataSource:self.filterDataSource];
                [_streamingContext removeCaptureVideoFx:_fxFilter.index];
                _fxFilter = nil;
            }
            for (NvBeautyTypeModel *model in self.beautyFxArray) {
                if ([model.fxName isEqualToString:@"Default Beauty Enabled"]) {
                    [self.fx setBooleanVal:model.fxName val:model.selected];
                    [self.fx setFloatVal:@"Default Intensity" val:model.value];
                }else if ([model.fxName isEqualToString:@"Default Sharpen Enabled"]){
                    [self.fx setBooleanVal:model.fxName val:model.selected];
                }else{
                    [self.fx setFloatVal:model.fxName val:model.value];
                }
            }
            
        }else{
            [self.fxARFace setFloatVal:@"Face Shape Level" val:4];
            [self.fxARFace setMenuVal:@"Face Type" val:@"Custom"];
            for (NvBeautyTypeModel *model in self.beautyTypeFxArray) {
                [self.fx setFloatVal:model.fxName val:model.value];
            }
        }
    }
}

- (void)switchActionShowToast:(NvSwitchView* )sender {
    [self showTip];
}

- (void)showTip {
    if (!self.tipAIView) {
        self.tipAIView = [[NvTipsView alloc]initWithFrame:self.view.frame withPrompt:@"提示" describeTitle:@"请移步官网，联系商务人员索要有人脸识别授权" describeContent:nil buttonText:@"知道了" withCenter:YES];
        [self.tipAIView.clickBtn addTarget:self action:@selector(removeTip) forControlEvents:UIControlEventTouchUpInside];
        [self.view addSubview:self.tipAIView];
    }
}

- (void)removeTip {
    [self.tipAIView removeFromSuperview];
    self.tipAIView = nil;
}

#pragma mark 注册应用前台后台通知事件
- (void)addObservers {
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(applicationWillResignActive:) name:UIApplicationWillResignActiveNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(applicationDidBecomeActive:) name:UIApplicationDidBecomeActiveNotification object:nil];
}

// 应用进入后台，停止采集
- (void)applicationWillResignActive:(NSNotification*)notification {
    if ([_streamingContext getStreamingEngineState] == NvsStreamingEngineState_CaptureRecording) {
        self.shootingBtn.selected = NO;
        [self faceHiddenBtn:NO];
        [self stopRecording];
        self.videoCount.text = [NSString stringWithFormat:@"%lu",(unsigned long)_videoPathArray.count];
        self.timeLabel.textColor = UIColor.whiteColor;
        self.videoCount.hidden = NO;
        self.duration = self.duration + self.lastDuration;
        [self.durationArray addObject:[NSNumber numberWithLongLong:self.lastDuration]];
    }
    
    if ([_streamingContext getStreamingEngineState] == NvsStreamingEngineState_CapturePreview) {
        [_streamingContext stop];
    }
}

// 应用进入前台，开始采集
- (void)applicationDidBecomeActive:(NSNotification*)notification {
    
    if ([_streamingContext getStreamingEngineState] == NvsStreamingEngineState_Stopped) {
        [self startCapturePreview];
    }
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
